#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

风险评估引擎
为每种后门选择提供成功率和风险评估
基于环境特征、安全配置和历史数据进行智能评估
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import json
import time
import math
import random
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass
from enum import Enum



try:
    from core.utils import color_green, color_yellow, color_red, color_blue
    from .intelligent_decision_engine import BackdoorType, ThreatLevel, SystemEnvironment
except ImportError as e:
    print("导入模块失败: {}".format(e))


class RiskCategory(Enum):
    """风险类别"""
    DETECTION = "detection"           # 被检测风险
    STABILITY = "stability"           # 稳定性风险
    PERFORMANCE = "performance"       # 性能影响风险
    FORENSICS = "forensics"          # 取证发现风险
    MAINTENANCE = "maintenance"       # 维护难度风险


class SuccessFactors(Enum):
    """成功因素"""
    ENVIRONMENT_COMPATIBILITY = "environment_compatibility"
    SECURITY_BYPASS = "security_bypass"
    STEALTH_CAPABILITY = "stealth_capability"
    PERSISTENCE_RELIABILITY = "persistence_reliability"
    RECOVERY_ABILITY = "recovery_ability"


@dataclass
class RiskFactor:
    """风险因素"""
    category: RiskCategory
    factor_name: str
    impact_score: float  # 0.0-1.0
    probability: float   # 0.0-1.0
    mitigation_possible: bool
    description: str


@dataclass
class SuccessFactor:
    """成功因素"""
    factor_type: SuccessFactors
    factor_name: str
    contribution_score: float  # 0.0-1.0
    confidence: float         # 0.0-1.0
    description: str


@dataclass
class RiskAssessment:
    """风险评估结果"""
    backdoor_type: BackdoorType
    overall_risk_score: float      # 0.0-1.0 (越高风险越大)
    success_probability: float     # 0.0-1.0 (成功概率)
    risk_factors: List[RiskFactor]
    success_factors: List[SuccessFactor]
    risk_level: ThreatLevel
    recommendations: List[str]
    confidence_level: float        # 评估置信度
    assessment_time: float


class EnvironmentRiskAnalyzer:
    """环境风险分析器"""
    
    def __init__(self):
        self.name = "环境风险分析器"
        self.risk_database = self._load_risk_database()
    
    def _load_risk_database(self) -> Dict[str, Any]:
        """加载风险数据库"""
        return {
            'os_risks': {
                'ubuntu': {'base_risk': 0.3, 'security_features': ['apparmor', 'ufw']},
                'centos': {'base_risk': 0.25, 'security_features': ['selinux', 'firewalld']},
                'debian': {'base_risk': 0.35, 'security_features': ['apparmor']},
                'rhel': {'base_risk': 0.2, 'security_features': ['selinux', 'firewalld']},
                'alpine': {'base_risk': 0.4, 'security_features': ['grsecurity']},
                'unknown': {'base_risk': 0.5, 'security_features': []}
            },
            'security_features': {
                'selinux': {'risk_multiplier': 1.5, 'bypass_difficulty': 0.8},
                'apparmor': {'risk_multiplier': 1.3, 'bypass_difficulty': 0.6},
                'grsecurity': {'risk_multiplier': 1.7, 'bypass_difficulty': 0.9},
                'firewall': {'risk_multiplier': 1.2, 'bypass_difficulty': 0.4},
                'antivirus': {'risk_multiplier': 1.4, 'bypass_difficulty': 0.7},
                'edr': {'risk_multiplier': 2.0, 'bypass_difficulty': 0.95}
            },
            'backdoor_risks': {
                BackdoorType.SSH_KEY: {
                    'base_success': 0.85,
                    'detection_risk': 0.2,
                    'stability_risk': 0.1,
                    'forensics_risk': 0.3
                },
                BackdoorType.CRONTAB: {
                    'base_success': 0.9,
                    'detection_risk': 0.15,
                    'stability_risk': 0.05,
                    'forensics_risk': 0.25
                },
                BackdoorType.STRACE: {
                    'base_success': 0.7,
                    'detection_risk': 0.4,
                    'stability_risk': 0.3,
                    'forensics_risk': 0.6
                },
                BackdoorType.SYSTEM_SERVICE: {
                    'base_success': 0.8,
                    'detection_risk': 0.3,
                    'stability_risk': 0.15,
                    'forensics_risk': 0.4
                },
                BackdoorType.NETWORK: {
                    'base_success': 0.75,
                    'detection_risk': 0.5,
                    'stability_risk': 0.2,
                    'forensics_risk': 0.35
                },
                BackdoorType.BASH_ALIAS: {
                    'base_success': 0.95,
                    'detection_risk': 0.1,
                    'stability_risk': 0.05,
                    'forensics_risk': 0.2
                },
                BackdoorType.ENVIRONMENT: {
                    'base_success': 0.9,
                    'detection_risk': 0.15,
                    'stability_risk': 0.1,
                    'forensics_risk': 0.25
                },
                BackdoorType.SSH_CONFIG: {
                    'base_success': 0.8,
                    'detection_risk': 0.25,
                    'stability_risk': 0.1,
                    'forensics_risk': 0.35
                },
                BackdoorType.USER_ACCOUNT: {
                    'base_success': 0.6,
                    'detection_risk': 0.7,
                    'stability_risk': 0.2,
                    'forensics_risk': 0.8
                },
                # 新增后门类型的风险数据
                # BackdoorType.KERNEL_MODULE: {  # 已禁用，不采用内核级后门
                #     'base_success': 0.9,
                #     'detection_risk': 0.8,
                #     'stability_risk': 0.4,
                #     'forensics_risk': 0.9
                # },
                BackdoorType.LIBRARY_HIJACK: {
                    'base_success': 0.75,
                    'detection_risk': 0.6,
                    'stability_risk': 0.3,
                    'forensics_risk': 0.7
                },
                BackdoorType.CONTAINER_ESCAPE: {
                    'base_success': 0.65,
                    'detection_risk': 0.7,
                    'stability_risk': 0.5,
                    'forensics_risk': 0.6
                },
                BackdoorType.DOCKER_SOCKET: {
                    'base_success': 0.85,
                    'detection_risk': 0.4,
                    'stability_risk': 0.2,
                    'forensics_risk': 0.5
                },
                BackdoorType.SYSTEMD_TIMER: {
                    'base_success': 0.88,
                    'detection_risk': 0.25,
                    'stability_risk': 0.1,
                    'forensics_risk': 0.3
                },
                # BackdoorType.PAM_MODULE: {  # 已禁用，不采用PAM模块后门
                #     'base_success': 0.8,
                #     'detection_risk': 0.5,
                #     'stability_risk': 0.2,
                #     'forensics_risk': 0.6
                # },
                BackdoorType.IPTABLES_RULE: {
                    'base_success': 0.7,
                    'detection_risk': 0.3,
                    'stability_risk': 0.15,
                    'forensics_risk': 0.4
                },
                BackdoorType.DNS_HIJACK: {
                    'base_success': 0.6,
                    'detection_risk': 0.6,
                    'stability_risk': 0.4,
                    'forensics_risk': 0.7
                },
                BackdoorType.PROCESS_INJECT: {
                    'base_success': 0.7,
                    'detection_risk': 0.8,
                    'stability_risk': 0.6,
                    'forensics_risk': 0.5
                },
                BackdoorType.MEMORY_RESIDENT: {
                    'base_success': 0.8,
                    'detection_risk': 0.9,
                    'stability_risk': 0.7,
                    'forensics_risk': 0.3
                }
            }
        }
    
    def analyze_environment_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析环境风险因素"""
        risk_factors = []
        
        # 操作系统风险
        os_risk = self._analyze_os_risks(system_env)
        risk_factors.extend(os_risk)
        
        # 安全特性风险
        security_risk = self._analyze_security_features(system_env)
        risk_factors.extend(security_risk)
        
        # 网络环境风险
        network_risk = self._analyze_network_risks(system_env)
        risk_factors.extend(network_risk)
        
        # 系统负载风险
        load_risk = self._analyze_system_load_risks(system_env)
        risk_factors.extend(load_risk)
        
        return risk_factors
    
    def _analyze_os_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析操作系统风险"""
        risks = []
        
        distro = system_env.distro.lower()
        os_data = self.risk_database['os_risks'].get(distro, self.risk_database['os_risks']['unknown'])
        
        # 基础OS风险
        base_risk = os_data['base_risk']
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="{}_base_risk".format(system_env.distro),
            impact_score=base_risk,
            probability=0.8,
            mitigation_possible=False,
            description="{} 操作系统基础风险".format(system_env.distro)
        ))
        
        # 版本特定风险
        if system_env.version:
            version_risk = self._calculate_version_risk(system_env.distro, system_env.version)
            risks.append(RiskFactor(
                category=RiskCategory.STABILITY,
                factor_name="version_compatibility",
                impact_score=version_risk,
                probability=0.6,
                mitigation_possible=True,
                description="版本 {} 兼容性风险".format(system_env.version)
            ))
        
        return risks
    
    def _analyze_security_features(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析安全特性风险"""
        risks = []
        
        # SELinux风险
        if system_env.selinux_enabled:
            selinux_data = self.risk_database['security_features']['selinux']
            risks.append(RiskFactor(
                category=RiskCategory.DETECTION,
                factor_name="selinux_protection",
                impact_score=selinux_data['bypass_difficulty'],
                probability=0.9,
                mitigation_possible=True,
                description="SELinux 强制访问控制保护"
            ))
        
        # AppArmor风险
        if system_env.apparmor_enabled:
            apparmor_data = self.risk_database['security_features']['apparmor']
            risks.append(RiskFactor(
                category=RiskCategory.DETECTION,
                factor_name="apparmor_protection",
                impact_score=apparmor_data['bypass_difficulty'],
                probability=0.8,
                mitigation_possible=True,
                description="AppArmor 应用程序安全框架保护"
            ))
        
        # 防火墙风险
        if system_env.firewall_active:
            firewall_data = self.risk_database['security_features']['firewall']
            risks.append(RiskFactor(
                category=RiskCategory.DETECTION,
                factor_name="firewall_protection",
                impact_score=firewall_data['bypass_difficulty'],
                probability=0.7,
                mitigation_possible=True,
                description="防火墙网络访问控制"
            ))
        
        # EDR/杀毒软件风险
        if hasattr(system_env, 'edr_enabled') and system_env.edr_enabled:
            edr_data = self.risk_database['security_features']['edr']
            risks.append(RiskFactor(
                category=RiskCategory.DETECTION,
                factor_name="edr_protection",
                impact_score=edr_data['bypass_difficulty'],
                probability=0.95,
                mitigation_possible=False,
                description="EDR 端点检测与响应保护"
            ))
        
        return risks
    
    def _analyze_network_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析网络环境风险"""
        risks = []
        
        # 网络监控风险
        if hasattr(system_env, 'network_monitoring') and system_env.network_monitoring:
            risks.append(RiskFactor(
                category=RiskCategory.DETECTION,
                factor_name="network_monitoring",
                impact_score=0.6,
                probability=0.8,
                mitigation_possible=True,
                description="网络流量监控可能检测异常连接"
            ))
        
        # 网络隔离风险
        if hasattr(system_env, 'network_isolation') and system_env.network_isolation:
            risks.append(RiskFactor(
                category=RiskCategory.MAINTENANCE,
                factor_name="network_isolation",
                impact_score=0.7,
                probability=0.9,
                mitigation_possible=False,
                description="网络隔离限制后门通信能力"
            ))
        
        return risks
    
    def _analyze_system_load_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析系统负载风险"""
        risks = []
        
        # 高负载环境风险
        if hasattr(system_env, 'system_load') and system_env.system_load == 'high':
            risks.append(RiskFactor(
                category=RiskCategory.PERFORMANCE,
                factor_name="high_system_load",
                impact_score=0.5,
                probability=0.7,
                mitigation_possible=True,
                description="高系统负载可能影响后门稳定性"
            ))
        
        # 资源受限风险
        if hasattr(system_env, 'resource_constraints') and system_env.resource_constraints:
            risks.append(RiskFactor(
                category=RiskCategory.STABILITY,
                factor_name="resource_constraints",
                impact_score=0.4,
                probability=0.6,
                mitigation_possible=True,
                description="系统资源受限可能影响后门运行"
            ))
        
        return risks
    
    def _calculate_version_risk(self, os_type: str, version: str) -> float:
        """计算版本风险"""
        # 简化的版本风险计算
        try:
            # 提取主版本号
            major_version = float(version.split('.')[0])
            
            # 较新版本通常有更好的安全特性
            if major_version >= 20:  # 较新版本
                return 0.3
            elif major_version >= 18:  # 中等版本
                return 0.2
            else:  # 较老版本
                return 0.1
        except:
            return 0.25  # 默认风险


class BackdoorRiskEvaluator:
    """后门风险评估器"""
    
    def __init__(self):
        self.name = "后门风险评估器"
        self.env_analyzer = EnvironmentRiskAnalyzer()
    
    def evaluate_backdoor_risk(self, backdoor_type: BackdoorType, 
                              system_env: SystemEnvironment) -> RiskAssessment:
        """评估特定后门的风险"""
        color_blue("🔍 评估 {} 后门风险...".format(backdoor_type.value))
        
        # 获取基础风险数据
        base_data = self.env_analyzer.risk_database['backdoor_risks'].get(
            backdoor_type, 
            {'base_success': 0.5, 'detection_risk': 0.5, 'stability_risk': 0.3, 'forensics_risk': 0.4}
        )
        
        # 分析环境风险因素
        env_risks = self.env_analyzer.analyze_environment_risks(system_env)
        
        # 分析后门特定风险
        backdoor_risks = self._analyze_backdoor_specific_risks(backdoor_type, system_env)
        
        # 合并所有风险因素
        all_risks = env_risks + backdoor_risks
        
        # 分析成功因素
        success_factors = self._analyze_success_factors(backdoor_type, system_env)
        
        # 计算整体风险分数
        overall_risk = self._calculate_overall_risk(all_risks, base_data)
        
        # 计算成功概率
        success_prob = self._calculate_success_probability(success_factors, base_data, overall_risk)
        
        # 确定风险级别
        risk_level = self._determine_risk_level(overall_risk, success_prob)
        
        # 生成建议
        recommendations = self._generate_recommendations(backdoor_type, all_risks, success_factors)
        
        # 计算置信度
        confidence = self._calculate_confidence(all_risks, success_factors)
        
        assessment = RiskAssessment(
            backdoor_type=backdoor_type,
            overall_risk_score=overall_risk,
            success_probability=success_prob,
            risk_factors=all_risks,
            success_factors=success_factors,
            risk_level=risk_level,
            recommendations=recommendations,
            confidence_level=confidence,
            assessment_time=time.time()
        )
        
        color_green("✓ {} 风险评估完成".format(backdoor_type.value))
        return assessment
    
    def _analyze_backdoor_specific_risks(self, backdoor_type: BackdoorType, 
                                       system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析后门特定风险"""
        risks = []
        
        if backdoor_type == BackdoorType.SSH_KEY:
            risks.extend(self._analyze_ssh_key_risks(system_env))
        elif backdoor_type == BackdoorType.CRONTAB:
            risks.extend(self._analyze_crontab_risks(system_env))
        elif backdoor_type == BackdoorType.STRACE:
            risks.extend(self._analyze_strace_risks(system_env))
        elif backdoor_type == BackdoorType.SYSTEM_SERVICE:
            risks.extend(self._analyze_service_risks(system_env))
        elif backdoor_type == BackdoorType.NETWORK:
            risks.extend(self._analyze_network_backdoor_risks(system_env))
        elif backdoor_type == BackdoorType.BASH_ALIAS:
            risks.extend(self._analyze_bash_alias_risks(system_env))
        elif backdoor_type == BackdoorType.ENVIRONMENT:
            risks.extend(self._analyze_environment_risks(system_env))
        elif backdoor_type == BackdoorType.SSH_CONFIG:
            risks.extend(self._analyze_ssh_config_risks(system_env))
        elif backdoor_type == BackdoorType.USER_ACCOUNT:
            risks.extend(self._analyze_user_account_risks(system_env))
        
        return risks
    
    def _analyze_ssh_key_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析SSH密钥后门风险"""
        risks = []
        
        # SSH配置检查风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="ssh_key_detection",
            impact_score=0.3,
            probability=0.4,
            mitigation_possible=True,
            description="SSH密钥可能被管理员检查发现"
        ))
        
        # 密钥文件权限风险
        risks.append(RiskFactor(
            category=RiskCategory.FORENSICS,
            factor_name="key_file_forensics",
            impact_score=0.4,
            probability=0.6,
            mitigation_possible=True,
            description="密钥文件可能留下取证痕迹"
        ))
        
        return risks
    
    def _analyze_crontab_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析Crontab后门风险"""
        risks = []
        
        # Cron日志风险
        risks.append(RiskFactor(
            category=RiskCategory.FORENSICS,
            factor_name="cron_logging",
            impact_score=0.5,
            probability=0.8,
            mitigation_possible=True,
            description="Cron任务执行会产生系统日志"
        ))
        
        # 定时执行检测风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="periodic_execution",
            impact_score=0.3,
            probability=0.5,
            mitigation_possible=True,
            description="定时执行模式可能被监控系统发现"
        ))
        
        return risks
    
    def _analyze_strace_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析Strace后门风险"""
        risks = []
        
        # 性能影响风险
        risks.append(RiskFactor(
            category=RiskCategory.PERFORMANCE,
            factor_name="strace_performance_impact",
            impact_score=0.7,
            probability=0.9,
            mitigation_possible=True,
            description="Strace跟踪会显著影响系统性能"
        ))
        
        # 进程监控检测风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="process_monitoring",
            impact_score=0.6,
            probability=0.7,
            mitigation_possible=False,
            description="Strace进程容易被进程监控发现"
        ))
        
        return risks
    
    def _analyze_service_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析系统服务后门风险"""
        risks = []
        
        # 服务管理检测风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="service_management",
            impact_score=0.4,
            probability=0.6,
            mitigation_possible=True,
            description="新增系统服务可能被管理员发现"
        ))
        
        # 服务日志风险
        risks.append(RiskFactor(
            category=RiskCategory.FORENSICS,
            factor_name="service_logging",
            impact_score=0.5,
            probability=0.8,
            mitigation_possible=True,
            description="系统服务会产生启动和运行日志"
        ))
        
        return risks
    
    def _analyze_network_backdoor_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析网络后门风险"""
        risks = []
        
        # 网络连接检测风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="network_connection_detection",
            impact_score=0.6,
            probability=0.8,
            mitigation_possible=True,
            description="网络监听端口容易被网络扫描发现"
        ))
        
        # 防火墙阻断风险
        if system_env.firewall_active:
            risks.append(RiskFactor(
                category=RiskCategory.STABILITY,
                factor_name="firewall_blocking",
                impact_score=0.8,
                probability=0.9,
                mitigation_possible=True,
                description="防火墙可能阻断网络后门连接"
            ))
        
        return risks
    
    def _analyze_bash_alias_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析Bash别名后门风险"""
        risks = []
        
        # 配置文件检查风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="config_file_inspection",
            impact_score=0.2,
            probability=0.3,
            mitigation_possible=True,
            description="Bash配置文件可能被管理员检查"
        ))
        
        return risks
    
    def _analyze_environment_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析环境变量后门风险"""
        risks = []
        
        # PATH劫持检测风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="path_hijacking_detection",
            impact_score=0.3,
            probability=0.4,
            mitigation_possible=True,
            description="PATH劫持可能被安全工具检测"
        ))
        
        return risks
    
    def _analyze_ssh_config_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析SSH配置后门风险"""
        risks = []
        
        # SSH配置审计风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="ssh_config_audit",
            impact_score=0.5,
            probability=0.7,
            mitigation_possible=True,
            description="SSH配置变更可能被安全审计发现"
        ))
        
        return risks
    
    def _analyze_user_account_risks(self, system_env: SystemEnvironment) -> List[RiskFactor]:
        """分析用户账户后门风险"""
        risks = []
        
        # 用户账户审计风险
        risks.append(RiskFactor(
            category=RiskCategory.DETECTION,
            factor_name="user_account_audit",
            impact_score=0.8,
            probability=0.9,
            mitigation_possible=False,
            description="新增用户账户容易被系统审计发现"
        ))
        
        # 登录记录风险
        risks.append(RiskFactor(
            category=RiskCategory.FORENSICS,
            factor_name="login_records",
            impact_score=0.7,
            probability=0.8,
            mitigation_possible=True,
            description="用户登录会产生详细的审计日志"
        ))
        
        return risks
    
    def _analyze_success_factors(self, backdoor_type: BackdoorType, 
                               system_env: SystemEnvironment) -> List[SuccessFactor]:
        """分析成功因素"""
        factors = []
        
        # 环境兼容性
        env_compat = self._calculate_environment_compatibility(backdoor_type, system_env)
        factors.append(SuccessFactor(
            factor_type=SuccessFactors.ENVIRONMENT_COMPATIBILITY,
            factor_name="environment_compatibility",
            contribution_score=env_compat,
            confidence=0.8,
            description="后门与目标环境的兼容性"
        ))
        
        # 安全绕过能力
        security_bypass = self._calculate_security_bypass_ability(backdoor_type, system_env)
        factors.append(SuccessFactor(
            factor_type=SuccessFactors.SECURITY_BYPASS,
            factor_name="security_bypass",
            contribution_score=security_bypass,
            confidence=0.7,
            description="绕过安全防护的能力"
        ))
        
        # 隐蔽性能力
        stealth_capability = self._calculate_stealth_capability(backdoor_type)
        factors.append(SuccessFactor(
            factor_type=SuccessFactors.STEALTH_CAPABILITY,
            factor_name="stealth_capability",
            contribution_score=stealth_capability,
            confidence=0.9,
            description="后门的隐蔽性和反检测能力"
        ))
        
        # 持久性可靠性
        persistence_reliability = self._calculate_persistence_reliability(backdoor_type)
        factors.append(SuccessFactor(
            factor_type=SuccessFactors.PERSISTENCE_RELIABILITY,
            factor_name="persistence_reliability",
            contribution_score=persistence_reliability,
            confidence=0.8,
            description="后门的持久性和可靠性"
        ))
        
        return factors
    
    def _calculate_environment_compatibility(self, backdoor_type: BackdoorType, 
                                           system_env: SystemEnvironment) -> float:
        """计算环境兼容性"""
        base_compatibility = 0.7
        
        # 根据操作系统调整
        if system_env.distro.lower() in ['ubuntu', 'debian']:
            if backdoor_type in [BackdoorType.SSH_KEY, BackdoorType.CRONTAB]:
                base_compatibility += 0.2
        elif system_env.distro.lower() in ['centos', 'rhel']:
            if backdoor_type == BackdoorType.SYSTEM_SERVICE:
                base_compatibility += 0.2
        
        # 根据安全特性调整
        if system_env.selinux_enabled and backdoor_type == BackdoorType.USER_ACCOUNT:
            base_compatibility -= 0.3
        
        return min(1.0, max(0.0, base_compatibility))
    
    def _calculate_security_bypass_ability(self, backdoor_type: BackdoorType, 
                                         system_env: SystemEnvironment) -> float:
        """计算安全绕过能力"""
        bypass_scores = {
            BackdoorType.BASH_ALIAS: 0.9,
            BackdoorType.ENVIRONMENT: 0.85,
            BackdoorType.SSH_KEY: 0.8,
            BackdoorType.CRONTAB: 0.75,
            BackdoorType.SSH_CONFIG: 0.7,
            BackdoorType.SYSTEM_SERVICE: 0.6,
            BackdoorType.NETWORK: 0.5,
            BackdoorType.STRACE: 0.4,
            BackdoorType.USER_ACCOUNT: 0.3
        }
        
        base_score = bypass_scores.get(backdoor_type, 0.5)
        
        # 根据安全特性调整
        if system_env.selinux_enabled:
            base_score *= 0.7
        if system_env.apparmor_enabled:
            base_score *= 0.8
        if system_env.firewall_active:
            base_score *= 0.9
        
        return min(1.0, max(0.0, base_score))
    
    def _calculate_stealth_capability(self, backdoor_type: BackdoorType) -> float:
        """计算隐蔽性能力"""
        stealth_scores = {
            BackdoorType.BASH_ALIAS: 0.95,
            BackdoorType.ENVIRONMENT: 0.9,
            BackdoorType.SSH_KEY: 0.85,
            BackdoorType.CRONTAB: 0.8,
            BackdoorType.SSH_CONFIG: 0.75,
            BackdoorType.SYSTEM_SERVICE: 0.7,
            BackdoorType.NETWORK: 0.6,
            BackdoorType.STRACE: 0.4,
            BackdoorType.USER_ACCOUNT: 0.2
        }
        
        return stealth_scores.get(backdoor_type, 0.5)
    
    def _calculate_persistence_reliability(self, backdoor_type: BackdoorType) -> float:
        """计算持久性可靠性"""
        persistence_scores = {
            BackdoorType.SYSTEM_SERVICE: 0.95,
            BackdoorType.USER_ACCOUNT: 0.9,
            BackdoorType.SSH_KEY: 0.85,
            BackdoorType.SSH_CONFIG: 0.8,
            BackdoorType.CRONTAB: 0.75,
            BackdoorType.ENVIRONMENT: 0.7,
            BackdoorType.BASH_ALIAS: 0.65,
            BackdoorType.NETWORK: 0.6,
            BackdoorType.STRACE: 0.4
        }
        
        return persistence_scores.get(backdoor_type, 0.5)
    
    def _calculate_overall_risk(self, risk_factors: List[RiskFactor], 
                              base_data: Dict[str, float]) -> float:
        """计算整体风险分数"""
        if not risk_factors:
            return base_data.get('detection_risk', 0.5)
        
        # 加权风险计算
        total_weighted_risk = 0.0
        total_weight = 0.0
        
        for risk in risk_factors:
            weight = risk.probability
            weighted_risk = risk.impact_score * weight
            total_weighted_risk += weighted_risk
            total_weight += weight
        
        if total_weight == 0:
            return base_data.get('detection_risk', 0.5)
        
        average_risk = total_weighted_risk / total_weight
        
        # 结合基础风险
        base_risk = (base_data.get('detection_risk', 0.5) + 
                    base_data.get('stability_risk', 0.3) + 
                    base_data.get('forensics_risk', 0.4)) / 3
        
        # 综合风险 = 0.6 * 环境风险 + 0.4 * 基础风险
        overall_risk = 0.6 * average_risk + 0.4 * base_risk
        
        return min(1.0, max(0.0, overall_risk))
    
    def _calculate_success_probability(self, success_factors: List[SuccessFactor], 
                                     base_data: Dict[str, float], 
                                     overall_risk: float) -> float:
        """计算成功概率"""
        base_success = base_data.get('base_success', 0.5)
        
        if not success_factors:
            return max(0.0, base_success - overall_risk)
        
        # 加权成功因素计算
        total_weighted_success = 0.0
        total_weight = 0.0
        
        for factor in success_factors:
            weight = factor.confidence
            weighted_success = factor.contribution_score * weight
            total_weighted_success += weighted_success
            total_weight += weight
        
        if total_weight == 0:
            average_success = 0.5
        else:
            average_success = total_weighted_success / total_weight
        
        # 综合成功概率 = 基础成功率 * 成功因素 * (1 - 风险因子)
        success_probability = base_success * average_success * (1 - overall_risk * 0.5)
        
        return min(1.0, max(0.0, success_probability))
    
    def _determine_risk_level(self, overall_risk: float, success_prob: float) -> ThreatLevel:
        """确定风险级别"""
        # 综合风险和成功概率确定威胁级别
        risk_score = overall_risk - success_prob + 0.5
        
        if risk_score >= 0.8:
            return ThreatLevel.CRITICAL
        elif risk_score >= 0.6:
            return ThreatLevel.HIGH
        elif risk_score >= 0.4:
            return ThreatLevel.MEDIUM
        else:
            return ThreatLevel.LOW
    
    def _generate_recommendations(self, backdoor_type: BackdoorType, 
                                risk_factors: List[RiskFactor], 
                                success_factors: List[SuccessFactor]) -> List[str]:
        """生成建议"""
        recommendations = []
        
        # 基于风险因素的建议
        high_risk_factors = [r for r in risk_factors if r.impact_score > 0.6]
        for risk in high_risk_factors:
            if risk.mitigation_possible:
                if risk.category == RiskCategory.DETECTION:
                    recommendations.append("建议增强隐蔽性措施以降低{}风险".format(risk.factor_name))
                elif risk.category == RiskCategory.PERFORMANCE:
                    recommendations.append("建议优化参数以减少{}影响".format(risk.factor_name))
                elif risk.category == RiskCategory.FORENSICS:
                    recommendations.append("建议加强痕迹清理以应对{}风险".format(risk.factor_name))
        
        # 基于成功因素的建议
        low_success_factors = [s for s in success_factors if s.contribution_score < 0.5]
        for factor in low_success_factors:
            if factor.factor_type == SuccessFactors.ENVIRONMENT_COMPATIBILITY:
                recommendations.append("建议选择更兼容的后门类型")
            elif factor.factor_type == SuccessFactors.SECURITY_BYPASS:
                recommendations.append("建议加强安全绕过技术")
        
        # 后门特定建议
        if backdoor_type == BackdoorType.STRACE:
            recommendations.append("建议在低负载时段部署Strace后门")
        elif backdoor_type == BackdoorType.USER_ACCOUNT:
            recommendations.append("建议谨慎使用用户账户后门，考虑其他隐蔽性更好的选项")
        elif backdoor_type == BackdoorType.NETWORK:
            recommendations.append("建议使用常见端口和加密通信")
        
        return recommendations[:5]  # 限制建议数量
    
    def _calculate_confidence(self, risk_factors: List[RiskFactor], 
                            success_factors: List[SuccessFactor]) -> float:
        """计算评估置信度"""
        if not risk_factors and not success_factors:
            return 0.3  # 低置信度
        
        # 基于数据完整性计算置信度
        data_completeness = min(1.0, (len(risk_factors) + len(success_factors)) / 10)
        
        # 基于因素置信度计算
        if success_factors:
            avg_factor_confidence = sum(f.confidence for f in success_factors) / len(success_factors)
        else:
            avg_factor_confidence = 0.5
        
        # 综合置信度
        overall_confidence = 0.6 * data_completeness + 0.4 * avg_factor_confidence
        
        return min(1.0, max(0.3, overall_confidence))


class RiskAssessmentEngine:
    """风险评估引擎"""
    
    def __init__(self):
        self.name = "风险评估引擎"
        self.evaluator = BackdoorRiskEvaluator()
        self.assessment_history = []
    
    def assess_all_backdoors(self, system_env: SystemEnvironment) -> List[RiskAssessment]:
        """评估所有后门类型的风险"""
        color_blue("🔍 开始全面风险评估...")
        
        assessments = []
        
        for backdoor_type in BackdoorType:
            try:
                assessment = self.evaluator.evaluate_backdoor_risk(backdoor_type, system_env)
                assessments.append(assessment)
                self.assessment_history.append(assessment)
            except Exception as e:
                color_red("评估 {} 失败: {}".format(backdoor_type.value, e))
        
        # 按成功概率排序
        assessments.sort(key=lambda x: x.success_probability, reverse=True)
        
        color_green("✓ 完成 {} 个后门的风险评估".format(len(assessments)))
        return assessments
    
    def get_risk_summary(self, assessments: List[RiskAssessment]) -> Dict[str, Any]:
        """获取风险评估摘要"""
        if not assessments:
            return {}
        
        # 统计信息
        total_count = len(assessments)
        high_success_count = len([a for a in assessments if a.success_probability > 0.7])
        low_risk_count = len([a for a in assessments if a.risk_level == ThreatLevel.LOW])
        
        # 推荐的后门
        recommended = [a for a in assessments if a.success_probability > 0.6 and a.risk_level in [ThreatLevel.LOW, ThreatLevel.MEDIUM]]
        
        # 风险分布
        risk_distribution = {}
        for level in ThreatLevel:
            risk_distribution[level.value] = len([a for a in assessments if a.risk_level == level])
        
        return {
            'total_backdoors_assessed': total_count,
            'high_success_probability_count': high_success_count,
            'low_risk_count': low_risk_count,
            'recommended_backdoors': [a.backdoor_type.value for a in recommended[:3]],
            'risk_distribution': risk_distribution,
            'average_success_probability': sum(a.success_probability for a in assessments) / total_count,
            'average_confidence': sum(a.confidence_level for a in assessments) / total_count
        }
    
    def export_assessment_report(self, assessments: List[RiskAssessment], 
                               filename: str = None) -> str:
        """导出评估报告"""
        if not filename:
            filename = "risk_assessment_report_{}.json".format(int(time.time()))
        
        report_data = {
            'assessment_time': time.time(),
            'total_assessments': len(assessments),
            'summary': self.get_risk_summary(assessments),
            'detailed_assessments': []
        }
        
        for assessment in assessments:
            assessment_data = {
                'backdoor_type': assessment.backdoor_type.value,
                'overall_risk_score': assessment.overall_risk_score,
                'success_probability': assessment.success_probability,
                'risk_level': assessment.risk_level.value,
                'confidence_level': assessment.confidence_level,
                'risk_factors': [
                    {
                        'category': rf.category.value,
                        'factor_name': rf.factor_name,
                        'impact_score': rf.impact_score,
                        'probability': rf.probability,
                        'description': rf.description
                    }
                    for rf in assessment.risk_factors
                ],
                'success_factors': [
                    {
                        'factor_type': sf.factor_type.value,
                        'factor_name': sf.factor_name,
                        'contribution_score': sf.contribution_score,
                        'confidence': sf.confidence,
                        'description': sf.description
                    }
                    for sf in assessment.success_factors
                ],
                'recommendations': assessment.recommendations
            }
            report_data['detailed_assessments'].append(assessment_data)
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(report_data, f, ensure_ascii=False, indent=2)
            
            color_green("✓ 风险评估报告已保存: {}".format(filename))
            return filename
        except Exception as e:
            color_red("保存报告失败: {}".format(e))
            return ""


def main():
    """测试风险评估引擎"""
    print("🔍 风险评估引擎测试")
    print("=" * 50)
    
    # 创建测试环境
    test_env = SystemEnvironment(
        distro="Ubuntu",
        version="20.04",
        architecture="x86_64",
        kernel_version="5.4.0",
        selinux_enabled=False,
        apparmor_enabled=True,
        firewall_active=True
    )
    
    # 创建风险评估引擎
    engine = RiskAssessmentEngine()
    
    # 评估所有后门
    assessments = engine.assess_all_backdoors(test_env)
    
    # 显示结果
    print(f"\n📊 评估结果:")
    for assessment in assessments[:5]:  # 显示前5个
        print("\n🎯 {}:".format(assessment.backdoor_type.value))
        print("  成功概率: {:.1%}".format(assessment.success_probability))
        print("  风险分数: {:.2f}".format(assessment.overall_risk_score))
        print("  风险级别: {}".format(assessment.risk_level.value))
        print("  置信度: {:.1%}".format(assessment.confidence_level))
        if assessment.recommendations:
            print("  建议: {}".format(assessment.recommendations[0]))
    
    # 显示摘要
    summary = engine.get_risk_summary(assessments)
    print(f"\n📋 评估摘要:")
    for key, value in summary.items():
        print("  {}: {}".format(key, value))
    
    # 导出报告
    report_file = engine.export_assessment_report(assessments)
    if report_file:
        print("\n📄 详细报告: {}".format(report_file))


if __name__ == "__main__":
    main()